<?php
namespace app\interfaces\controller;

use think\Db;
use think\Exception;
use think\Request;
use app\common\trilateral\wxBizDataCrypt;
use think\Cache;
class WeChat
{

    function http_request($url, $fields = null, $cert = true)
     {
         $ch = curl_init();
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
         curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);
         curl_setopt($ch, CURLOPT_SSLCERT, 'cert'.DIRECTORY_SEPARATOR.'apiclient_cert.pem');
         curl_setopt($ch, CURLOPT_SSLKEY, 'cert'.DIRECTORY_SEPARATOR.'apiclient_key.pem');
         curl_setopt($ch, CURLOPT_CAINFO, 'cert'.DIRECTORY_SEPARATOR.'rootca.pem');
         if (!empty($fields)){
             curl_setopt($ch, CURLOPT_POST, 1);
             curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
         }
         $data = curl_exec($ch);
         if(!$data){echo "CURL ErrorCode: ".curl_errno($ch);}
         curl_close($ch);
         return $data;
     }
    // 微信登录
    public function obtain()
    {

        // 获取参数
        try {
            $data = Request::instance()->param();

            if (empty($data['token']) || empty($data['openid'])) throw new Exception('not Empty');
            //$data['openid'] = 'o540807b8c_IE2n8pufgeBtx8JuE';
            //$data['token'] = '15_E6d2va33z0vdB5oudzMIwBz6mshrEcTg80gVpB-pB3JGhCCHJykl56v58DJd4ZSwX1d56EGRXw61iy_PGidocuoKFTstVEQCCy-m12fM8zM';
            writeLog('opendid' . $data['openid']);
            writeLog('token' . $data['token']);
            // 解析微信
            $arr = json_decode(file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token=' . $data['token'] . '&openid=' . $data['openid']), true);

            // halt($arr);

            if (empty($arr['openid'])) return ['code' => 400, 'message' => '解析失败'];

            // 读取是否存在
            $id = Db::name('member')->where(['wechat_id' => $arr['unionid']])->value('id');

            // 如果不存在
            if (empty($id)) {
                return ['code' => 403, 'message' => '用户未注册', 'unionid' => $arr['unionid'], 'headimgurl' => $arr['headimgurl'], 'nickname' => $arr['nickname'], 'sex' => $arr['sex']];
            }

            return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $id]];
        } catch (\Exception $e) {
            return ['code' => $e->getCode(),'message' => $e->getMessage(),'get_line' => $e->getLine()];
        }

        // // 启动事务
        // Db::startTrans();
        //
        // try {
        //
        //     $user_id = Db::name('member')->insertGetId([
        //         'wechat_id'   => $arr['unionid'],
        //         'avatar'      => $arr['headimgurl'],
        //         'nickname'    => str_replace("馃挀", "", $arr['nickname']),
        //         'sex'         => $arr['sex'],
        //         'create_ip'   => getIP(),
        //         'create_time' => time(),
        //     ]);
        //
        //
        //     // 提交事务
        //     Db::commit();
        //
        //     return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];
        //
        // } catch (\Exception $e) {
        //
        //     // 回滚事务
        //     Db::rollback();
        //
        //     return ['code' => 401, 'message' => '网络繁忙'];
        // }

        // }

    }


    public function obtain_zhuce()
    {

        $data = Request::instance()->param();
        $smsVerify = Cache::get('sms_verify_bind_tel_' . $data['tel']);
        if ($smsVerify != $data['code']) {
            return ['code' => 401, 'message' => '验证码错误'];
        }
        writeLog('ijson-'.json_encode($data));
        if (!$data['unionid'] || !$data['tel'] || !$data['password'] || !$data['code']) return ['code' => 403, 'message' => '参数错误'];

        $tel = Db::name('member')->where('username', $data['tel'])->value('id');
        $name = date('Ymd') . DS . md5(microtime(true)) . ".jpg";
        $path = "./uploads/";
        $map = "/uploads/" . $name;
        put_file_from_url_content($data['headimgurl'], $name, $path);
        if (!$tel) {


            // 启动事务
            Db::startTrans();

            try {
                $user_id = Db::name('member')->insertGetId([
                    'wechat_id'   => $data['unionid'],
                    'avatar'      => $map,
                    'nickname'    => str_replace("馃挀", "", $data['nickname']),
                    'sex'         => $data['sex'],
                    'create_ip'   => getIP(),
                    'create_time' => date('Y-m-d H:i:s',time()),
                    'username'    => $data['tel'],
                    'password'    => sha1($data['password']),
                ]);
                Db::name('member_distribution')->insert(['distribution_id' => '0', 'referrals_id' => $user_id, 'hierarchy' => '0,', 'level' => '1', 'create_time' => date('Y-m-d H:i:s', time())]);
                // 提交事务
                (new \app\index\controller\Coupon())->send(3,$user_id);
                Db::commit();

                return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];


            } catch (\Exception $e) {

                // 回滚事务
                Db::rollback();

                return ['code' => 402, 'message' => $e->getMessage()];
            }
        }else{
            $adf = Db::name('member')->where('username',$data['tel'])->update([
                'wechat_id'   => $data['unionid'],
                'avatar'      => $map,
                'nickname'    => str_replace("馃挀", "", $data['nickname']),
                'sex'         => $data['sex'],
                'create_ip'   => getIP(),
                'create_time' => date('Y-m-d H:i:s',time()),
                'password'    => sha1($data['password']),
            ]);
            writeLog('json'.json_encode($adf));
            $user_id = Db::name('member')->where('username',$data['tel'])->value('id');
            if($adf) return ['code' => 200, 'message' => '成功', 'data' => ['user_id' => $user_id]];
            if(!$adf) return ['code' => 401, 'message' => '注册失败'];
        }


    }
    /*
 * 小程序加密数据解密
 * code
 * encryptedData
 * iv
 */
    public function obtain_decode()
    {
        $in = Request::instance()->param();
        $item = json_decode(file_get_contents("https://api.weixin.qq.com/sns/jscode2session?appid=wxfad7142a43ba4835&secret=9ee49a690ce634505474649472047c9a&js_code=" . $in['code'] . "&grant_type=authorization_code"));

        $appid = 'wxfad7142a43ba4835';
        $sessionKey = $item->session_key;
//66666666666666
        $encryptedData = $in['encryptedData'];

        $iv = $in['iv'];

        $pc = new WXBizDataCrypt($appid, $sessionKey);

        $errCode = $pc->decryptData($encryptedData, $iv, $data);
        $data = json_decode($data);
        return ['code' => 200, 'message' => "成功", 'data' => $data];
    }
    ////
    public  function  ceshi(){
        $name = date('Ymd'). DS . md5(microtime(true)). ".jpg";
        $path = "./uploads/";
        $map = "/uploads/".$name;
        halt(put_file_from_url_content("https://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJMsZRXU5AAdKIoCV0uWNQdFEzTyv17cicbGnYHkkY0diaNIhQyTySf87fTRzFITcZMzYvCCU8WA6Mg/0",$name, $path));
    }

    /*
 * 小程序注册
 */
    /*
     * 小程序注册
     */



}